package com.example.lianguisystem.controller;

import cn.hutool.core.lang.UUID;
import com.example.lianguisystem.DTO.PanDIanDTO;
import com.example.lianguisystem.VO.PanDianVO;
import com.example.lianguisystem.common.FineReportConstant;
import com.example.lianguisystem.common.Result;
import com.example.lianguisystem.entity.CommonSetting;
import com.example.lianguisystem.entity.LianGuiLabelRecord;
import com.example.lianguisystem.entity.PanDianRecord;
import com.example.lianguisystem.mapper.GzrsLabelMapper;
import com.example.lianguisystem.mapperLianGui.CommonMapper;
import com.example.lianguisystem.mapperLianGui.LabelMapper;
import com.example.lianguisystem.mapperLianGui.LabelStatusMapper;
import com.example.lianguisystem.mapperLianGui.PanDIanMapper;
import com.example.lianguisystem.service.CommonSettingService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/panDian")
@CrossOrigin
public class PanDianController {

    @Autowired
    private PanDIanMapper panDIanMapper;
    @Autowired
    private CommonMapper commonMapper;
    @Autowired
    private CommonSettingService commonSettingService;

    @Autowired
    private GzrsLabelMapper gzrsLabelMapper;
    @Autowired
    private LabelMapper labelMapper;

    @Autowired
    private LabelStatusMapper labelStatusMapper;

    @GetMapping("/print")
    public Result print(@RequestParam("workshopId") Integer workshopId,@RequestParam(value = "username",required = false) String usernma
    ,@RequestParam(value = "panDianTime",required = false) String panDianTime, @RequestParam("printer") String printer) {
        try {
            printer = URLEncoder.encode(printer, "UTF-8").replace("+", "%20");
            //调用url，相当于浏览器携带参数直接打开网址
            String url = FineReportConstant.FINE_REPORT_URI + "DQ/lianGuiPanDian.cpt^&YG=" + usernma+ "^&PC=" + panDianTime+ "^&SCCJ=" + (workshopId == null ? "" : workshopId) + "^&dyj=" + printer;
            Runtime.getRuntime().exec("cmd /c start  " + url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.success();
    }

    @GetMapping("/list")
    public Result list(@RequestParam(value = "workshop",required = false) Integer workshop, @RequestParam(value = "username",required = false) String username, @RequestParam(value = "panDianTime",required = false) String  panDianTime, @RequestParam(value = "status",required = false) Integer status) {
        List<PanDianRecord> recordList = panDIanMapper.selectPanDianRecord(workshop, username, panDianTime, status);
        List<Map<String, Object>> workshopList = commonMapper.listOfWorkshopOsSelection();
        Map<String, Integer> workshopMap = new HashMap<>();
        for (Map<String, Object> map : workshopList) {
            workshopMap.put((String) map.get("text"), (Integer) map.get("value"));
        }
        // 0按 工作中心分组
        Map<String, List<PanDianRecord>> groupedRecordsOfWorkshop = recordList.stream()
                .collect(Collectors.groupingBy(PanDianRecord::getWorkshopName));
        List<PanDianVO> resList = new ArrayList<>();
        for (Map.Entry<String, List<PanDianRecord>> voEntry : groupedRecordsOfWorkshop.entrySet()) {
            List<PanDianRecord> valueList = voEntry.getValue();
            PanDianVO panDianVO = new PanDianVO();
            panDianVO.setWorkshop(voEntry.getKey());
            panDianVO.setWorkshopId(workshopMap.get(voEntry.getKey()));
            panDianVO.setQuantity(valueList.size());
            double sum = valueList.stream().mapToDouble(PanDianRecord::getWeight).sum();
            panDianVO.setWeight(sum);
            // 1. 按 designNo 分组
            Map<String, List<PanDianRecord>> groupedRecords = valueList.stream()
                    .collect(Collectors.groupingBy(PanDianRecord::getDesignNo));
            // 2. 将每个分组转换为 PanDIanDTO
            List<PanDIanDTO> panDIanDTOList = groupedRecords.entrySet().stream()
                    .map(entry -> {
                        PanDIanDTO dto = new PanDIanDTO();
                        String designNo = entry.getKey();
                        List<PanDianRecord> groupRecords = entry.getValue();

                        // 设置 DTO 属性
                        dto.setTitle(designNo);

                        // 3. 将每组中的 PanDianRecord 转换为 LianGuiLabelRecord
                        List<LianGuiLabelRecord> labelRecords = groupRecords.stream()
                                .map(this::convertToLabelRecord)
                                .collect(Collectors.toList());

                        dto.setList(labelRecords);
                        dto.setSubTitle(groupRecords.get(0).getCpTypeNo());

                        // 4. 计算总重量 (如果需要)
                        double totalWeight = groupRecords.stream()
                                .mapToDouble(r -> r.getWeight() != null ? r.getWeight() : 0.0)
                                .sum();
                        dto.setWeight(totalWeight);

                        return dto;
                    })
                    .collect(Collectors.toList());
            panDianVO.setRecordList(panDIanDTOList);
            resList.add(panDianVO);
        }


        return Result.success(resList);
    }
    // 辅助方法：单个记录转换
    private LianGuiLabelRecord convertToLabelRecord(PanDianRecord record) {
        LianGuiLabelRecord labelRecord = new LianGuiLabelRecord();
        // 属性映射
        labelRecord.setWeight(record.getWeight());
        labelRecord.setDesignNo(record.getDesignNo());
        labelRecord.setCpTypeNo(record.getCpTypeNo());
        labelRecord.setMachine(record.getMachine());
        labelRecord.setLabel(record.getLabel());
        labelRecord.setCreateBy(record.getCreateBy());
        labelRecord.setCreateDate(record.getCreateDate());

        // 根据需要添加其他属性映射
        // labelRecord.setOtherField(record.getOtherField());

        return labelRecord;
    }


    @GetMapping("/listNoSubmit")
    public Result listNoSubmit(@RequestParam(value = "workshop",required = false) Integer workshop, @RequestParam(value = "username",required = false) String username, @RequestParam(value = "panDianTime",required = false) Integer panDianTime, @RequestParam(value = "status",required = false) Integer status) {
        List<LianGuiLabelRecord> recordList = panDIanMapper.selectNoSubmitRecord(workshop, username, panDianTime, status);
        List<Map<String, Object>> workshopList = commonMapper.listOfWorkshopOsSelection();
        Map<String, Integer> workshopMap = new HashMap<>();
        for (Map<String, Object> map : workshopList) {
            workshopMap.put((String) map.get("text"), (Integer) map.get("value"));
        }
        // 0按 工作中心分组
        Map<String, List<LianGuiLabelRecord>> groupedRecordsOfWorkshop = recordList.stream()
                .collect(Collectors.groupingBy(LianGuiLabelRecord::getWorkshop));
        List<PanDianVO> resList = new ArrayList<>();
        for (Map.Entry<String, List<LianGuiLabelRecord>> voEntry : groupedRecordsOfWorkshop.entrySet()) {
            List<LianGuiLabelRecord> valueList = voEntry.getValue();
            PanDianVO panDianVO = new PanDianVO();
            panDianVO.setWorkshop(voEntry.getKey());
            panDianVO.setWorkshopId(workshopMap.get(voEntry.getKey()));
            panDianVO.setQuantity(valueList.size());
            double sum = valueList.stream().mapToDouble(LianGuiLabelRecord::getWeight).sum();
            panDianVO.setWeight(sum);
            // 1. 按 designNo 分组
            Map<String, List<LianGuiLabelRecord>> groupedRecords = valueList.stream()
                    .collect(Collectors.groupingBy(LianGuiLabelRecord::getDesignNo));
            // 2. 将每个分组转换为 PanDIanDTO
            List<PanDIanDTO> panDIanDTOList = groupedRecords.entrySet().stream()
                    .map(entry -> {
                        PanDIanDTO dto = new PanDIanDTO();
                        String designNo = entry.getKey();
                        List<LianGuiLabelRecord> groupRecords = entry.getValue();

                        // 设置 DTO 属性
                        dto.setTitle(designNo);


                        dto.setList(groupRecords);
                        dto.setSubTitle(groupRecords.get(0).getCpTypeNo());

                        // 4. 计算总重量 (如果需要)
                        double totalWeight = groupRecords.stream()
                                .mapToDouble(r -> r.getWeight() != null ? r.getWeight() : 0.0)
                                .sum();
                        dto.setWeight(totalWeight);

                        return dto;
                    })
                    .collect(Collectors.toList());
            panDianVO.setRecordList(panDIanDTOList);
            resList.add(panDianVO);
        }


        return Result.success(resList);
    }

    @ApiOperation(value = "盘点-查询打印机列表", notes = "盘点-查询打印机列表")
    @GetMapping("/queryPrinter")
    public Result queryPrinter(@RequestParam("username") String username) {
        List<String> list = gzrsLabelMapper.selectPrinter();
        CommonSetting commonSetting = commonSettingService.getCommonSetting(username, "莲桂标签打印");
        List<Object> resList = new ArrayList<>();
        resList.add(list);
        resList.add(commonSetting);
        return Result.success(resList);
    }

    @GetMapping("/querySelection")
    public Result querySelection(@RequestParam("username") String username) {
        List<Map<String, Object>> list = commonMapper.listOfWorkshopOsSelection();
        List<String> panDianTimeList = panDIanMapper.listPanDianTime(username);
        List<String> panDianPersonList = panDIanMapper.listPanDianPerson();
        String panDianTime = panDIanMapper.selectTopPanDianTimeOfAll(username);
        Map<String, Object> map = new HashMap<>();
        map.put("workshopArr", list);
        map.put("panDianTimeArr", panDianTimeList);
        map.put("panDianTime", panDianTime);
        map.put("panDianPersonArr", panDianPersonList);
        return Result.success(map);
    }

    @PostMapping("/removePanDian")
    public Result removePanDian(@RequestBody PanDIanDTO panDIanDTO) {
        List<LianGuiLabelRecord> list = panDIanDTO.getList();
        List<String> collect = list.stream().map(LianGuiLabelRecord::getPanDianId).collect(Collectors.toList());
        Integer integer = panDIanMapper.deleteRecordById(collect);
        return Result.success();
    }

    @GetMapping("/scanLabel")
    public Result scanLabel(@RequestParam("label") String label,@RequestParam("username") String username, @RequestParam(value = "workshop",required = false) Integer workshop) {
        LianGuiLabelRecord lianGuiLabelRecord = labelMapper.selectByLabel(label);
        PanDianRecord panDian = panDIanMapper.isPanDian(username, lianGuiLabelRecord.getId(),null);
        if (panDian != null) {
            return Result.fail("该标签已被"+panDian.getCreateBy()+"扫描，3天内只允许一人扫描");
        }

        String maxPanDianTime = panDIanMapper.selectTopPanDianTime(username);
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String format = LocalDate.now().format(dtf);
        String uuid = UUID.fastUUID().toString().replace("-", "");
        PanDianRecord panDianRecord = new PanDianRecord();
        panDianRecord.setId(uuid);
        panDianRecord.setCreateBy(username);
        panDianRecord.setCreateDate(new Date());
        panDianRecord.setLabelId(lianGuiLabelRecord.getId());
        panDianRecord.setWorkshop(workshop);
        panDianRecord.setRecordDate(format);
        panDianRecord.setStatus(0);
        panDianRecord.setPanDianTime(maxPanDianTime);
        panDIanMapper.insert(panDianRecord);
        lianGuiLabelRecord.setPanDianId(panDianRecord.getId());
        return Result.success(lianGuiLabelRecord);
    }

    @GetMapping("/removeOneRecord")
    public Result removeOneRecord(@RequestParam("id") String id) {
        int i = panDIanMapper.deleteById(id);
        return Result.success();
    }

    @PostMapping("/submit")
    @Transactional(rollbackFor = Exception.class, transactionManager = "lianGuiTransactionManager")
    public Result submit(@RequestBody List<PanDIanDTO> panDIanDTOList, @RequestParam(value = "workshop",required = false) Integer workshop, @RequestParam("username") String username) {

        List<String> panDianIdList = panDIanDTOList.stream().map(PanDIanDTO::getList).flatMap(List::stream).map(LianGuiLabelRecord::getPanDianId).collect(Collectors.toList());
        List<String> panDianed = panDIanMapper.selectPanDianed(panDianIdList);
        if (panDianed != null && panDianed.size() > 0) {
            return Result.fail("标签已盘点：" + panDianed);
        }
        for (PanDIanDTO panDIanDTO : panDIanDTOList) {
            List<LianGuiLabelRecord> list = panDIanDTO.getList();
            for (LianGuiLabelRecord lianGuiLabelRecord : list) {
                PanDianRecord panDianRecord = new PanDianRecord();
                panDianRecord.setId(lianGuiLabelRecord.getPanDianId());
                panDianRecord.setUpdateBy(username);
                panDianRecord.setUpdateDate(new Date());
                panDianRecord.setStatus(1);
                panDIanMapper.updateById(panDianRecord);
            }
        }
//        int i = 1 / 0;
        return Result.success();
    }

}
